package org.xs.web.http.validate;

import java.lang.reflect.Method;

import org.apache.log4j.Logger;
import org.xs.web.util.Helpers;

public class ValidateMethod {
	 	private static final Logger logger = Logger.getLogger(ValidateMethod.class);
	 	
		private Method method;
		private String[] args;
		private String msg;
		private String field;
		private Object validator;
		
		public ValidateMethod(String field,Method method,Object validator,String msg,String... args){
			this.method = method;
			this.msg = msg;
			this.args = args == null ? new String[0]: args;
			this.field = field;
			this.validator = validator;
		}
		
		public boolean apply(Object value){
			Object res = null;
			Object[] values = Helpers.arrayMerge(args, new Object[]{value});
			try {
				res = method.invoke(validator, values);
			} catch (Exception e) {
				logger.debug("validate moethod invoke error "+e);
				return false;
			}
			if(res instanceof Boolean){
				return (Boolean)res;
			}
			return res == null ? true : false;
		}

		public String getField() {
			return field;
		}
		
		public String getMsg(){
			return msg;
		}
}
